<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button v-has-perm="'add:menu'" class="filter-item" type="primary" @click="handleCreate">
        添加菜单
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="tableData"
      row-key="id"
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column prop="title" label="菜单名称" min-width="180" />
      <el-table-column prop="path" label="路由路径" min-width="180" />
      <el-table-column prop="icon" label="图标" width="100">
        <template #default="{ row }">
          <el-icon v-if="row.icon">
            <component :is="row.icon" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="permission" label="权限标识" min-width="150" />
      <el-table-column prop="sort" label="排序" width="80" />
      <el-table-column label="显示" width="80">
        <template #default="{ row }">
          <el-tag v-if="!row.hidden" type="success">显示</el-tag>
          <el-tag v-else type="info">隐藏</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <template #default="{ row }">
          <el-button v-has-perm="'add:menu'" v-test-account size="small" type="primary" @click="handleAddChild(row)">
            添加子菜单
          </el-button>
          <el-button v-has-perm="'edit:menu'" v-test-account size="small" type="warning" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-has-perm="'delete:menu'" v-test-account size="small" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 菜单对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px">
      <el-form
        ref="dataForm"
        :model="tempMenu"
        :rules="rules"
        label-position="right"
        label-width="100px"
      >
        <el-form-item label="上级菜单">
          <el-tree-select
            v-model="tempMenu.parent_id"
            :data="menusTree"
            node-key="id"
            :props="{ label: 'title', children: 'children' }"
            check-strictly
            :render-after-expand="false"
            placeholder="不选择则为一级菜单"
            clearable
          />
        </el-form-item>
        <el-form-item label="菜单名称" prop="title">
          <el-input v-model="tempMenu.title" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="路由路径" prop="path">
          <el-input v-model="tempMenu.path" placeholder="请输入路由路径" />
        </el-form-item>
        <el-form-item label="组件地址" prop="component">
          <el-input v-model="tempMenu.component" placeholder="组件地址，如 views/user/list" />
        </el-form-item>
        <el-form-item label="图标">
          <el-select v-model="tempMenu.icon" placeholder="请选择图标" clearable>
            <el-option v-for="icon in iconList" :key="icon" :label="icon" :value="icon">
              <div class="icon-option">
                <el-icon>
                  <component :is="icon" />
                </el-icon>
                <span>{{ icon }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限标识">
          <el-input v-model="tempMenu.permission" placeholder="权限标识，如 view:user" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="tempMenu.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch v-model="tempMenu.hidden" :active-value="false" :inactive-value="true" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button v-test-account type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMenus, getMenu, createMenu, updateMenu, deleteMenu } from '@/api/menu'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

const listLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const menusList = ref([])
const tableData = ref([])
const menusTree = ref([])
const dataForm = ref(null)

// 获取Element Plus的所有图标
const iconList = Object.keys(ElementPlusIconsVue)

const tempMenu = reactive({
  id: undefined,
  parent_id: null,
  title: '',
  path: '',
  component: '',
  icon: '',
  permission: '',
  sort: 0,
  hidden: false,
  children: []
})

const rules = {
  title: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  path: [{ required: true, message: '请输入路由路径', trigger: 'blur' }]
}

// 获取菜单列表
const getMenuList = async () => {
  listLoading.value = true
  try {
    const response = await getMenus()
    menusList.value = response.data || []
    
    // 转换为树形结构
    tableData.value = convertToTree(menusList.value)
    menusTree.value = convertToTree(menusList.value)
  } catch (error) {
    console.error('获取菜单列表失败', error)
    ElMessage.error('获取菜单列表失败')
  } finally {
    listLoading.value = false
  }
}

// 将平铺列表转为树形结构
const convertToTree = (list) => {
  const map = {}
  const result = []
  
  // 先构建ID映射
  list.forEach(item => {
    map[item.id] = { ...item, children: [] }
  })
  
  // 构建树形结构
  list.forEach(item => {
    const menuItem = map[item.id]
    
    if (item.parent_id && map[item.parent_id]) {
      map[item.parent_id].children.push(menuItem)
    } else {
      result.push(menuItem)
    }
  })
  
  return result
}

// 创建菜单
const handleCreate = () => {
  dialogTitle.value = '添加菜单'
  dialogVisible.value = true
  
  // 重置表单
  nextTick(() => {
    if (dataForm.value) {
      dataForm.value.resetFields()
    }
    
    // 重置表单数据
    Object.assign(tempMenu, {
      id: undefined,
      parent_id: null,
      title: '',
      path: '',
      component: '',
      icon: '',
      permission: '',
      sort: 0,
      hidden: false,
      children: []
    })
  })
}

// 添加子菜单
const handleAddChild = (row) => {
  dialogTitle.value = `添加 ${row.title} 的子菜单`
  dialogVisible.value = true
  
  // 重置表单
  nextTick(() => {
    if (dataForm.value) {
      dataForm.value.resetFields()
    }
    
    // 重置表单数据并设置父ID
    Object.assign(tempMenu, {
      id: undefined,
      parent_id: row.id,
      title: '',
      path: '',
      component: '',
      icon: '',
      permission: '',
      sort: 0,
      hidden: false,
      children: []
    })
  })
}

// 更新菜单
const handleUpdate = async (row) => {
  dialogTitle.value = '编辑菜单'
  dialogVisible.value = true
  
  // 获取菜单详情
  try {
    const response = await getMenu(row.id)
    
    // 更新表单数据
    Object.assign(tempMenu, response.data)
  } catch (error) {
    console.error('获取菜单详情失败', error)
    ElMessage.error('获取菜单详情失败')
  }
}

// 删除菜单
const handleDelete = (row) => {
  if (row.children && row.children.length > 0) {
    ElMessage.warning('该菜单下有子菜单，请先删除子菜单')
    return
  }
  
  ElMessageBox.confirm('确定要删除该菜单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteMenu(row.id)
      ElMessage.success('删除成功')
      getMenuList()
    } catch (error) {
      console.error('删除菜单失败', error)
      ElMessage.error('删除菜单失败')
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = async () => {
  if (!dataForm.value) return
  
  // 表单验证
  try {
    await dataForm.value.validate()
    
    // 是新增还是编辑
    if (tempMenu.id === undefined) {
      // 新增
      await createMenu(tempMenu)
      ElMessage.success('创建成功')
    } else {
      // 编辑
      await updateMenu(tempMenu.id, tempMenu)
      ElMessage.success('更新成功')
    }
    
    // 关闭对话框并刷新列表
    dialogVisible.value = false
    getMenuList()
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

// 获取菜单数据
onMounted(() => {
  getMenuList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 20px;
}

.filter-item {
  margin-right: 10px;
}

.dialog-footer {
  text-align: right;
}

.icon-option {
  display: flex;
  align-items: center;
}

.icon-option span {
  margin-left: 8px;
}
</style> 